import React, { useEffect, useState } from 'react';
import { Modal, Button, Space, Tree, TreeProps, message, Skeleton } from 'antd';
import BreadCrumb from './BreadCrumb';
import { useContextSelector } from 'use-context-selector';
import { DatasetsContext } from '../context';
import datasetService from '@/api/services/datasetService';
import { DatasetTypeEnum } from '@/common';
import { DatasetEvent, TreeData } from '@/types/dataset';
import { getBackground, getNodeTypeName, transformToTreeItems } from '@/utils/tree';
import { DownOutlined } from '@ant-design/icons';
import { SvgIcon } from '@/components/icon';
import '../styles/move-to-modal.scss';
import { useDebounceFn, useThrottleFn, useTrackedEffect } from 'ahooks';
import useWindowWidth from '@/hooks/event/use-window-width';
import orgService from '@/api/services/orgService';

interface Props {
  visible: boolean;
  onCancel: () => void;
  appId?: string;
}

const MoveToModal: React.FC<Props> = ({ visible, onCancel, appId = '' }) => {
  /**
   * 移动的逻辑
   *
   * 一、知识库可以移动到文件夹 调用/api/core/dataset/list接口，请求参数
   * { "parentId": null, "type": "folder" }
   *
   * 二、文件夹分为两种情况
   * 1、文件夹不属于知识库，可以移动到文件夹， 同上
   * 2、文件夹在知识库内部，只可以移动到知识库中的其他文件夹中
   *
   * 三、文件
   * 文件只能在知识库的文件夹内部移动，调用接口/api/core/dataset/collection/list获取可以移动的文件夹，请求参数
   * {"datasetId": "6746b569ddb3e03c99d7f7ca","parentId": "","selectFolder": true,"simple": true,"pageNum": 1,"pageSize": 50}
   */
  const { event$, currentEditTreeData, selectedTreeNode, currentDataset } = useContextSelector(
    DatasetsContext,
    (s) => s,
  );
  const [treeDatas, setTreeDatas] = useState<TreeData[]>([]);
  const [selectedData, setSelectedData] = useState<TreeData | undefined>();
  const [loading, setLoading] = useState<boolean>(false);
  const { isPc } = useWindowWidth();
  const [messageApi, contextHolder] = message.useMessage();
  const titleRender = (node: TreeData) => {
    const { name, key, type, count } = node;
    if (type == 'file') {
      return <div style={{ display: 'none' }}></div>;
    }

    return (
      <div className="flex items-center self-center p-2" style={{ fontSize: '20' }}>
        <div className="mr-2 flex-shrink-0 items-center justify-center rounded-lg">
          {type === 'folder' ? (
            <SvgIcon color="#FFCA28" className="m-1" icon="ri--folder-2-fill" size={24} />
          ) : (
            <SvgIcon color="#BF63FF" className="m-1" icon="mdi--folder-zip" size={24} />
          )}
        </div>
        <div className="flex-1">{name}</div>
        {/* {type == "folder" && <div className="flex-shrink-0 ml-2 bg-[#E5DCFF] rounded-xl">
          <span className="ml-3 mr-3">{count}</span>
        </div>} */}
      </div>
    );
  };

  const filterTreeItems = (items: TreeData[], excludeId: string): TreeData[] => {
    return items
      .filter((item) => item.id !== excludeId)
      .map((item) => ({
        ...item,
        children: item.children ? filterTreeItems(item.children, excludeId) : [],
      }));
  };

  const filterTreeFolder = (items: TreeData[], matchType: string): TreeData[] => {
    // 只保留 type 等于 matchType 的节点
    return items
      .filter((item) => item.type === matchType) // 筛选出 type 符合 matchType 的节点
      .map((item) => ({
        ...item,
        title: item.name,
        // 如果有 children，则递归筛选符合条件的子节点
        children: item.children ? filterTreeFolder(item.children, matchType) : [],
      }));
  };

  const fetchDataset = async () => {
    try {
      // if (!currentDataset || currentEditTreeData?.type == 'dataset') {
      // const res = await datasetService.datasetList({
      //   parentId: null,
      //   type: DatasetTypeEnum.folder,
      // });
      const data = await orgService.getDataset({ appId: appId });

      const treeItems = transformToTreeItems(data.list, undefined, true);
      // const treeItems = transformToTreeItems(res, undefined, true);

      // 根目录数据
      const rootDirData = {
        key: 'root',
        id: 'root',
        name: '根目录',
        type: 'folder',
        title: '根目录',
        children: filterTreeFolder(treeItems, 'folder'),
        // children: filterTreeItems(treeItems, currentEditTreeData?.id ?? ''),
        updateTime: new Date() + '',
        count: 0,
        forbid: false,
      };

      setTreeDatas([rootDirData]);
      // setTreeDatas(filterTreeItems(treeItems, currentEditTreeData?.id ?? ''));
      // } else {
      // const res = await datasetService.collectionList({
      //   datasetId: currentDataset?.id ?? '',
      //   pageNum: 1,
      //   pageSize: 50,
      //   parentId: '',
      //   selectFolder: true,
      //   simple: true,
      // });
      // const treeItems = transformToTreeItems(res.data, undefined, true);

      // setTreeDatas(filterTreeItems(treeItems, currentEditTreeData?.id ?? ''));
      // }
    } catch (ex) {
      console.error(ex);
    } finally {
      setLoading(false);
    }
  };

  const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    setSelectedData(info.node);
  };

  const onConfirm = async () => {
    let parentId = null;

    if (selectedData?.id !== 'root' && selectedData?._id != '') {
      parentId = selectedData?.id || selectedData?._id;
    }

    console.log("============", selectedData, currentEditTreeData);


    // if (!currentDataset || currentEditTreeData?.type == 'dataset') {
    // console.log('执行了');
    // console.log(selectedData);
    // console.log(currentEditTreeData);
    if (selectedData?.id === 'root' || selectedData?.groupId === currentEditTreeData?.groupId) {

      if (selectedData?._id === currentEditTreeData?.id) {
        message.error('移动失败,不可移动到自身');
        return
      } else {
        const data = await datasetService.updateFile({
          appId: appId,
          id: currentEditTreeData?.id ?? '',
          parentId: parentId,
        });

        // const res = await datasetService.datasetUpdate({
        //   id: currentEditTreeData?.id ?? '',
        //   parentId: parentId,
        // });
        // } else {
        //   const res = await datasetService.updateDatasetCollection({
        //     id: currentEditTreeData?.id ?? '',
        //     parentId: selectedData?.id,
        //   });
        // }

        event$?.emit(DatasetEvent.UPDATEDATASETTREE);
        event$?.emit(DatasetEvent.UPDATECOLLECTION);

        message.success('移动成功！');
        cancel();

      }

    } else {
      messageApi.error('移动失败，不在同一组织');
    }
  };

  const cancel = () => {
    onCancel();
    setTreeDatas([]);
    setSelectedData(undefined);
  };

  const { run } = useDebounceFn(
    async () => {
      setLoading(true);
      await fetchDataset();
    },
    { wait: 100 },
  );

  useEffect(() => {
    if (visible) {
      run();
    }
  }, [currentEditTreeData, visible]);

  return (
    <Modal
      className="move-to"
      open={visible}
      onCancel={cancel}
      closable={false}
      width={isPc ? '50%' : '100%'}
      footer={
        <div style={{ textAlign: 'right' }}>
          <Space size={30}>
            <Button onClick={cancel}>取消</Button>
            {selectedData && (
              <Button className="mr-4" type="primary" onClick={onConfirm}>
                移动到这
              </Button>
            )}
          </Space>
        </div>
      }
    >
      {contextHolder}
      <div className="flex flex-col">
        <p className="mb-2 mb-2 ml-2 mt-2">
          将{' '}
          <span className="font-bold">
            {' '}
            {getNodeTypeName(currentEditTreeData)} {currentEditTreeData?.name}
          </span>{' '}
          移动至
          <span className="font-bold">{selectedData?.name ?? '...'}</span>
        </p>
        <BreadCrumb disable={true} />
        {loading && <Skeleton className="mt-5" />}
        {!loading && (
          <div>
            {!treeDatas ||
              (treeDatas && treeDatas.length == 0 && (
                <div className="mt-5 text-center">无可移动到的位置</div>
              ))}
            {treeDatas && treeDatas.length > 0 && (
              <div className="mt-2 min-h-20">
                <Tree
                  className="tree rounded-xl"
                  // expandedKeys={expandedKeys}
                  // expandedKeys={['root']}
                  selectedKeys={[selectedData?._id]}
                  onSelect={onSelect}
                  treeData={treeDatas}
                  titleRender={titleRender}
                  switcherIcon={<DownOutlined />}
                ></Tree>
              </div>
            )}
          </div>
        )}
      </div>
    </Modal>
  );
};

export default MoveToModal;
